package net.expectx.common.single.third.baidu;

import com.baidu.aip.ocr.AipOcr;
import net.expectx.common.single.base.BaseResult;
import net.expectx.common.single.util.ImageUtil;
import org.json.JSONObject;
import sun.misc.BASE64Decoder;

import java.util.HashMap;

/**
 * @author lijian
 * @desc
 * @dateTime 6/5/2018 9:36 AM
 * @info 18363003321/974028417@qq.com
 */
public class BaiDuOcrUtils {
    /**
     * 身份证识别
     * @param sources    图片路径
     * @param isFront    身份证类型,true:正面,false:反面
     * @return
     */
    public static BaseResult idCardOcr(String sources, Boolean isFront, Boolean isNetwork){
        JSONObject resultJSON=new JSONObject();
        AipOcr client=AipOcrClientSingleton.getInstance().getAipOcr();
        HashMap<String, String> options = new HashMap<>(2);
        options.put("detect_direction", "true");
        options.put("detect_risk", "false");
        String idCardSide;

        if(isFront){
            idCardSide="front";
        }else{
            idCardSide="back";
        }
        try {
            JSONObject res=null;
            if (isNetwork){
                sources= ImageUtil.getImgStrByUrl(sources);
            }else{
                sources= ImageUtil.getImgStrByFile(sources);
            }
            BASE64Decoder decode = new BASE64Decoder();
            res= client.idcard(decode.decodeBuffer(sources), idCardSide, options);
            return BaiDuAiConstant.analysisJSON(res);
        }catch (Exception e){
            return new BaseResult(false,e.getLocalizedMessage(),null);
        }
    }
    public static void main(String[] args) {
        System.out.println(BaiDuAiResultAnalyze.analyzeOCR(idCardOcr("C:\\Users\\Administrator\\Pictures\\Camera Roll\\身份证demo-card-2.png",true,false)));
        System.out.println(idCardOcr("http://localhost:2222/upload/Expect-X-Test/image/player/20181215164415182_561.png",true,true));
        BaseResult result=BaiDuAiResultAnalyze.analyzeOCR(idCardOcr("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1545033017653&di=6832897cbf7c366ee3d1ff04530e5fb4&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20181216%2F653d283e52b5491c9cccc74e5d7668ac.jpeg",false,true));
        System.out.println(result);

    }
}




